﻿//-----------------------------------------------------------------------
// <copyright file="PropertyChangeNotifierBase.cs" author="Artak Mkrtchyan">
//     Creative Commons - GNU General Public License (http://creativecommons.org/licenses/GPL/2.0/
// </copyright>
// <author>Artak Mkrtchyan</author>
// <email>mkArtak@gmail.com</email>
// <date>21/05/2013</date>
//-----------------------------------------------------------------------
using System.ComponentModel;

namespace ConsoleHoster.Common.ViewModel
{
	public abstract class PropertyChangeNotifierBase : INotifyPropertyChanged
	{
		public event PropertyChangedEventHandler PropertyChanged;

		protected void NotifyPropertyChange(string argPropertyName)
		{
			PropertyChangedEventHandler tmpEH = this.PropertyChanged;
			if (tmpEH != null)
			{
				tmpEH(this, new PropertyChangedEventArgs(argPropertyName));
			}
		}

		protected bool SetPropertyValue<T>(string argPropertyName, ref T argField, T argNewValue)
		{
			bool areEqual = false;
			if (!typeof(T).IsValueType)
			{
				if (argNewValue == null && argField == null)
				{
					areEqual = true;
				}
				else if (argNewValue == null)
				{
					areEqual = false;
				}
				else
				{
					areEqual = argNewValue.Equals(argField);
				}
			}
			else
			{
				areEqual = argNewValue.Equals(argField);
			}

			if (!areEqual)
			{
				argField = argNewValue;
				this.NotifyPropertyChange(argPropertyName);
			}

			return !areEqual;
		}
	}
}
